
matern.estpcf=function (emppcf, startpar = c(sigma2 = 1, alpha = 1), lambda = NULL, nu=1/2, 
		q = 1/4, p = 2, rmin = NULL, rmax = NULL, ...) 
{
	
	startpar <- check.named.vector(startpar, c("sigma2", "alpha"))
	
	theoretpcf <- function(par,r,nu){
		if (any(par <= 0) | par[2]>5000) 
			return(rep(Inf, length(r)))
		
		if(nu==Inf){
			return(exp(par[1]*exp(-1/2*(r/par[2])^2)))
		}else{
			return(exp(Covariance(r,model="matern",param=c(0.0,par[1],0.0,par[2],nu))))
		}
	}
	
	result <-  mincontrast(emppcf, theoretpcf, startpar, ctrl = list(q = q, 
					p = p, rmin = rmin, rmax = rmax), fvlab = list(label = "%s[fit](r)", 
					desc = "minimum contrast fit of LGCP"), 
			...,nu=nu)
	
	par <- result$par
	names(par) <- c("sigma2", "alpha")
	result$par <- par
	mu <- if (is.numeric(lambda) && length(lambda) == 1 && lambda > 
					0) 
				log(lambda) - par[["sigma2"]]/2
			else NA
	result$modelpar <- c(sigma2 = par[["sigma2"]], alpha = par[["alpha"]], 
			mu = mu)
	result$internal <- list(model = "matern")
    attr(result,"nu")=nu
	return(result)
}


best.matern.estpcf=function(X, startpar = c(sigma2 = 1, alpha = 1), lambda = NULL, nu=c(0.25), 
		q = 1/4, p = 2, rmin = NULL, rmax = NULL, ...){
	bestmodel=list()
	minivalues=numeric()
	for(i in 1:length(nu)){
		bestmodel[[i]]=matern.estpcf(X, startpar,rmax=rmax,rmin=rmin,nu=nu[i])
		minivalues[i]=bestmodel[[i]]$opt$value
	}
	minione=which(minivalues==min(minivalues))[1]
	return(bestmodel[[minione]])
}